<template>
  <el-container>
    <div id="mapDialogHeadInterlayer"></div>
    <el-header class="custom-map-dialog-header">
      <el-row>
        <el-button size="mini"
                   round
                   type="primary"
                   v-if="mode !== 'middle'"
                   @click="saveMapInfo">保存信息</el-button>
        <el-button size="mini"
                   round
                   type="danger"
                   v-if="mode !== 'middle'"
                   @click="clearAll">清除信息</el-button>
        <span v-if="mode !== 'middle'"><i style="color:#fff;font-style:normal;padding-left:10px">经纬度：</i> <input type="text"
                 style="height:25px;line-height:25px; border:none;border-radius:3px"
                 v-model="lnglat"
                 readonly /></span>
      </el-row>
    </el-header>
    <el-main>
      <div id="container"
           class="app-map-wrapper"></div>
      <div class="map-tool"
           v-if="mapCompleteStatus">
        <div class="map-tool-mode">
          <el-radio-group v-model="editMode"
                          @change="draw">
            <el-radio-button v-if="mode === 'full' || mode !== 'middle'"
                             label="polygon">多边形</el-radio-button>
            <el-radio-button v-if="mode !== 'middle'"
                             label="marker">经纬度</el-radio-button>
            <el-radio-button v-if="mode !== 'middle'"
                             label="empty">取消</el-radio-button>
          </el-radio-group>
        </div>
        <div class="map-tool-operator"
             v-if="mode === 'full' || mode !== 'middle'">
          <el-radio-group v-if="editPolygon"
                          v-model="editChangeStatus"
                          @change="editChange">
            <el-radio-button v-if="mode !== 'middle'"
                             label="open">开启编辑</el-radio-button>
            <el-radio-button v-if="mode !== 'middle'"
                             label="close">关闭编辑</el-radio-button>
          </el-radio-group>
        </div>
        <div class="custom-color-picker">
          <el-button @click="colorClick">选择颜色</el-button>
          <ul v-show="isColorThumbShow"
              id="colorThumb">
            <li class="color-3477fd"></li>
            <li class="color-004bda"></li>
            <li class="color-013cb0"></li>
            <!-- <li class="color-ffb460"></li>
            <li class="color-8595d9"></li>
            <li class="color-63a0b2"></li>
            <li class="color-78d08f"></li>
            <li class="color-d55e7e"></li> -->
          </ul>
        </div>
      </div>
    </el-main>
  </el-container>
</template>
<script>
import { getMapLocationByTarget, delMapLocationByTarget } from '@/http/AppApi'
import MapUtil from '@/utils/MapUtil'
export default {
  name: 'full-map',
  props: {
    rowId: '',
    mode: {
      type: String,
      default: 'simple' // full(全功能)/simple(获取经纬度)/ point(画点)/ middle(显示区域)
    },
    target: {
      type: Object,
      default: null
    }
  },
  data () {
    return {
      AMapUI: null,
      AMap: null,
      map: null,
      mouseTool: null,
      polyEditor: [],
      isColorThumbShow: false,
      mapCompleteStatus: false,
      isClearCurrentPolygon: false,
      mapCenter: '',
      editPolygonAttr: {
        strokeColor: '#80d8ff',
        strokeOpacity: 0.9,
        fillColor: '#00b0ff',
        fillOpacity: 0.2,
        bubble: true
      },
      editPolygon: [],
      currentPolygon: [],
      editPolygonData: [],
      editPolygonAttrColor: '',
      lnglat: '',
      editMarker: null,
      editMode: '',
      editChangeStatus: 'close',
      currentPolygonId: []
    }
  },
  computed: {},
  watch: {},
  mounted () {
    this.init()
    console.log(window.AMap)
  },
  created () { },
  updated () { },
  methods: {
    init (mode) {
      this.AMapUI = window.AMapUI
      this.AMap = window.AMap
      let mapConfig = {
        zoom: 13,
        cityName: '信阳',
        center: [114.091104, 32.148489]
      }
      this.map = new this.AMap.Map('container', mapConfig)
      this.map.on('complete', this.mapLoadComplete)
      if (mode) {
        this.mode = mode
      }
    },
    addUIs () {
      let map = this.map
      this.AMapUI.loadUI(['control/BasicControl'], function (BasicControl) {
        map.addControl(new BasicControl.LayerSwitcher({
          position: 'lt'
        }))
      })
    },
    mapLoadComplete () {
      console.log(this.mode)
      this.mapCompleteStatus = this.mode !== 'simple'
      if (this.mode === 'simple') {
        this.onSelectLngLat()
      }
      this.mapCenter = this.map.getCenter()
      this.addUIs()
      let _this = this
      this.map.plugin(['AMap.MouseTool'], function () {
        _this.mouseTool = new _this.AMap.MouseTool(_this.map)
      })
      if ((this.mode === 'full' && this.target) || (this.mode === 'middle' && this.target)) {
        this.drawTarget()
      } else if (this.mode === 'point' && this.target) {
        this.drawTarget()
      }
    },
    offAll () {
      // 关闭所有事件
      this.offSelectLngLat()
      this.offDrawPoly()
      this.editMode = 'empty'
    },
    clearAll () {
      // 使用clearMap方法删除所有覆盖物
      // this.map.clearMap();
      // 清除地图上创建的覆盖物与标记
      if (this.editMarker) {
        this.map.remove(this.editMarker)
        this.editMarker = null
      }
      if (this.currentPolygon.length > 0) {
        let m = this
        for (const key in this.currentPolygon) {
          if (this.currentPolygon.hasOwnProperty(key)) {
            m.map.remove(this.currentPolygon[key])
          }
        }
        this.currentPolygon = []
        this.isClearCurrentPolygon = true
      }
      if (this.lnglat) {
        this.lnglat = ''
      }
      this.offAll()
      this.closeEditPoly()
      this.clearMapLocationByTarget()
    },
    clearMapLocationByTarget () {
      let mapLocation = {}
      mapLocation.targetId = this.target.targetId
      mapLocation.targetType = this.target.targetType
      delMapLocationByTarget(mapLocation).then(resp => {
        if (resp.code && resp.code === '200') {
          this.$message({ showClose: true, message: '清除成功', type: 'success' })
          this.destroy()
          this.init(this.mode)
        }
      })
    },
    draw (type) {
      if (type) {
        // 关闭编辑多边形
        this.closeEditPoly()
        switch (type) {
          case 'marker':
            this.offDrawPoly()
            this.onSelectLngLat()
            break
          case 'polygon':
            this.offSelectLngLat()
            this.onDrawPoly()
            break
          default:
            this.offAll()
            break
        }
      }
    },
    editChange (data) {
      // 选择开启/关闭编辑多边形
      if (data) {
        if (data === 'open' && !this.isClearCurrentPolygon) {
          this.openEditPoly()
        }
        if (data === 'close') {
          this.closeEditPoly()
        }
        return ''
      }
    },
    // 颜色选择  填充
    colorClick () {
      let colorThumb = document.getElementById('colorThumb')
      if (colorThumb && colorThumb.childNodes) {
        let lis = colorThumb.childNodes
        let m = this
        for (let i = 0; i < lis.length; i++) {
          lis[i].addEventListener('click', function () {
            let colorO = {}
            let className = this.className
            let color = '#' + className.slice(6)
            m.editPolygonAttrColor = color
            colorO.fillColor = color
            colorO.strokeColor = color
            if (m.currentPolygon.length > 0) {
              for (const key in m.currentPolygon) {
                if (m.currentPolygon.hasOwnProperty(key)) {
                  m.currentPolygon[key].setOptions(colorO)
                }
              }
            }
          })
        }
      }
      this.isColorThumbShow = !this.isColorThumbShow
    },
    openEditPoly () {
      if (this.isClearCurrentPolygon) return ''
      // 开启编辑多边形
      if (this.currentPolygon.length !== 0) {
        let m = this
        for (const key in this.currentPolygon) {
          if (this.currentPolygon.hasOwnProperty(key)) {
            this.map.plugin(['AMap.PolyEditor'], function () {
              let polyEditor = null
              polyEditor = new this.AMap.PolyEditor(m.map, m.currentPolygon[key])
              polyEditor.open()
              m.polyEditor.push(polyEditor)
              // 关闭下方操作按钮
              m.offAll()
            })
          }
        }
      }
      return ''
    },
    closeEditPoly () {
      // 关闭多边形
      if (this.polyEditor.length > 0) {
        for (const key in this.polyEditor) {
          if (this.polyEditor.hasOwnProperty(key)) {
            this.polyEditor[key].close()
          }
        }
        // this.polyEditor.close()
        this.editChangeStatus = 'close'
      }
    },
    onSelectLngLat () {
      // 打开选择经纬度事件
      this.map.on('click', this.selectLngLat)
    },
    offSelectLngLat () {
      // 关闭选择经纬度事件
      this.map.off('click', this.selectLngLat)
    },
    selectLngLat (e) {
      // 选择经纬度并显示
      let lnglat = e.lnglat.getLng() + ',' + e.lnglat.getLat()
      this.lnglat = lnglat
      let marker = {}
      if (this.editMarker) {
        let id = this.editMarker.getExtData()
        marker = new this.AMap.Marker({
          position: [e.lnglat.getLng(), e.lnglat.getLat()],
          extData: id
        })
        this.map.remove(this.editMarker)
      } else {
        marker = new this.AMap.Marker({
          position: [e.lnglat.getLng(), e.lnglat.getLat()]
        })
      }
      this.map.add(marker)
      this.editMarker = marker
    },
    onDrawPoly () {
      // 打开绘画多边形
      this.isClearCurrentPolygon = false
      this.mouseTool.close(false)
      this.mouseTool.polygon(this.editPolygonAttr)
      this.mouseTool.on('draw', this.createDrawPolygon, this.map)
    },
    offDrawPoly () {
      // 关闭绘画多边形
      this.mouseTool.off('draw', this.createDrawPolygon, this.map)
      this.mouseTool.close(true)
    },
    createDrawPolygon (e) {
      // 画多边形回调
      // if (this.editPolygon.length > 0) {
      //   let len = this.editPolygon.length - 1
      //   this.map.remove(this.editPolygon[len])
      // }
      this.isClearCurrentPolygon = false
      let path = e.obj.getPath()
      if (path && path instanceof Array) {
        this.map.remove(e.obj)
        this.editPolygonAttr.path = path
        let polygon = new this.AMap.Polygon(this.editPolygonAttr)
        this.currentPolygon.push(polygon)
        polygon.targetId = this.rowId
        this.editPolygon.push(polygon)
        this.map.add(polygon)
      }
    },
    destroy () {
      this.map.destroy()
    },
    saveMapInfo () {
      this.offAll()
      this.closeEditPoly()
      let mapInfo = {}
      mapInfo.clearStatus = true
      if (this.editMarker) {
        let p = this.editMarker.getPosition()
        // 用来标记某个点
        mapInfo.markPosition = {}
        mapInfo.markPosition.lng = p.lng
        mapInfo.markPosition.lat = p.lat
        // 只用来选择经纬度
        mapInfo.lnglat = {}
        mapInfo.lnglat.lng = p.lng
        mapInfo.lnglat.lat = p.lat
        mapInfo.clearStatus = false
        let id = this.editMarker.getExtData()
        if (id && id.length > 0) {
          mapInfo.id = id
        }
      }
      if (this.editPolygon.length > 0) {
        let m = this
        let poly = []
        for (let j = 0; j < this.editPolygon.length; j++) {
          if (m.rowId === this.editPolygon[j].targetId) {
            poly.push(this.editPolygon[j])
          }
        }
        if (poly.length > 1) {
          let polyData = []
          for (let i = 0; i < poly.length; i++) {
            let obj = {}
            let path = MapUtil.paths2Array(poly[i].getPath())
            path = JSON.stringify(path).toString()
            obj.polyPathArr = path
            obj.id = poly[i].mapLocationId
            obj.polyColor = poly[i].getOptions().fillColor
            polyData.push(obj)
          }
          mapInfo.poly = polyData
        } else if (poly.length === 1) {
          let path = MapUtil.paths2Array(poly[0].getPath())
          path = JSON.stringify(path).toString()
          mapInfo.polyPathArr = path
          mapInfo.polyColor = poly[0].getOptions().fillColor
          if (poly[0].mapLocationId) {
            mapInfo.id = poly[0].mapLocationId
          }
        }
        let lngLat = this.lnglat !== '' ? this.lnglat.split(',') : []
        mapInfo.longitude = lngLat.length > 0 ? lngLat[0] : ''
        mapInfo.latitude = lngLat.length > 0 ? lngLat[1] : ''
        mapInfo.clearStatus = this.isClearCurrentPolygon
      }
      if (this.target) {
        mapInfo.target = this.target
      }
      this.$emit('appMapCallback', mapInfo)
      this.destroy()
    },
    drawTarget () {
      if (this.target) {
        let _this = this
        getMapLocationByTarget(this.target).then(resp => {
          if (resp.code && resp.code === '200') {
            let data = resp.data
            if (data) {
              this.editPolygonData = data
              for (let i = 0; i < data.length; i++) {
                if (data[i].parentNode) data[i].mapColor = '#ccc'
                _this.createTarget(data[i])
              }
            }
          }
        })
      }
    },
    location2Arr (lnglats) {
      let newLnglatsArr = []
      if (lnglats && lnglats instanceof Array && lnglats.length > 0) {
        for (const lnglat of lnglats) {
          let arr = []
          arr.push(lnglat.lng)
          arr.push(lnglat.lat)
          newLnglatsArr.push(arr)
        }
      }
      return newLnglatsArr
    },
    createTarget (p) {
      // 绘制对象：多边形和点
      // if (this.editPolygon) {
      //   this.map.remove(this.editPolygon)
      // }
      if (p) {
        if (p.mapColor) {
          this.editPolygonAttr.fillColor = p.mapColor
          this.editPolygonAttr.strokeColor = p.mapColor
          this.editPolygonAttrColor = p.mapColor
        }
        if (p.mapArea) {
          p.mapArea = p.mapArea.replace(/@/g, '],[')
          this.editPolygonAttr.path = JSON.parse(p.mapArea)
          let m = this
          let polygon = new this.AMap.Polygon(m.editPolygonAttr)
          polygon.targetId = p.targetId
          polygon.mapLocationId = p.id
          if (polygon.targetId === this.rowId) {
            this.currentPolygon.push(polygon)
          }
          this.editPolygon.push(polygon)
          this.map.add(polygon)
        }
        if (p.longitude && p.latitude && p.targetId === this.rowId) {
          let lnglat = [p.longitude, p.latitude]
          let id = p.id
          let marker = new this.AMap.Marker({
            position: lnglat,
            extData: id
          })
          if (this.editMarker) {
            this.map.remove(this.editMarker)
          }
          this.editMarker = marker
          this.map.add(marker)
          this.map.setCenter(lnglat)
          this.map.setZoom(13)
        }
      }
    }
  }
}
</script>
<style scoped>
.app-map-wrapper {
  height: 600px;
}
.map-tool {
  position: absolute;
  right: 3%;
  top: 66px;
  z-index: 999999;
  width: auto;
  height: auto;
  display: flex;
}
.map-tool .el-radio-group {
  vertical-align: top;
}
.map-tool .map-tool-mode {
  margin-right: 4px;
}
.custom-map-dialog-header {
  position: absolute;
  top: -1px;
  right: 44px;
  z-index: 9999;
  width: 39%;
  height: 44px !important;
  line-height: 44px;
}
.custom-color-picker {
  position: relative;
}
.custom-color-picker ul {
  width: 120px;
  border: 1px solid rgb(64, 158, 255);
  background-color: white;
  padding: 4px;
  margin: 0;
  list-style: none;
  position: absolute;
  top: 50px;
  left: -52px;
  display: flex;
  justify-content: space-around;
  z-index: 9999;
  cursor: pointer;
}
.custom-color-picker .el-button {
  padding: 12px 10px !important;
}
.custom-color-picker ul li {
  width: 24px;
  height: 24px;
  border-radius: 3px;
  cursor: pointer;
}
.custom-color-picker ul li:hover {
  opacity: 0.7;
}
.custom-color-picker ul li:nth-child(1) {
  background-color: #3477fd;
}
.custom-color-picker ul li:nth-child(2) {
  background-color: #004bda;
}
.custom-color-picker ul li:nth-child(3) {
  background-color: #013cb0;
}
/* .custom-color-picker ul li:nth-child(1){
  background-color: #ffb460
}
.custom-color-picker ul li:nth-child(2){
  background-color: #8595d9
}
.custom-color-picker ul li:nth-child(3){
  background-color: #63a0b2
}
.custom-color-picker ul li:nth-child(4){
  background-color: #78d08f
}
.custom-color-picker ul li:nth-child(5){
  background-color: #d55e7e
} */
</style>
